<template>
	<view class="wrap">
		<js-error mode="bottom" ref="jsError"></js-error>
		<xw-scan></xw-scan>
		<!-- <view class="cu-bar search" style="padding: 10px">
			<u-search v-model="barCode" ref="uSearch" :focus="focus" placeholder="请先聚焦后扫描" :show-action="false"
				@search="confirm"></u-search>
			<view style="margin-left: 10px; display: flex; flex-direction: column">
				<u-icon @click="search" name="scan" size="50"></u-icon>
			</view>
		</view> -->
		<view style="background-color: #fff;">
			<u-form class="form bg-white" :model="model" ref="uForm" label-position="left" style="padding: 0 10px;">
				<u-form-item label="公司:" prop="companyCode" label-width="180" required
					:label-style="{'font-weight':'bold'}">
					<js-select v-model="model.companyCode" :showFilter="false" :items="companySelectList"
						placeholder="请选择" :tree="true" :label-value="model['company.companyName']"
						@label-input="model['company.companyName'] = $event"
						@confirm="selectcompanyConfirm"></js-select>
				</u-form-item>

				<u-form-item label="仓库:" prop="whcode" label-width="180" required :label-style="{'font-weight':'bold'}">
					<js-select v-model="model.whcode" :showFilter="false" :items="whSelectList" placeholder="请选择"
						:tree="true" :label-value="model['basWare.cwhname']"
						@label-input="model['basWare.cwhname'] = $event" @confirm="selectConfirm"></js-select>
				</u-form-item>

				<u-form-item label="商品:" prop="cinvName" label-width="180" :label-style="{ 'font-weight': 'bold' }"
					required>
					<view @click="xzsp"
						style="display: flex;justify-content: space-between;width: 100%;font-size: 30rpx;">
						<view v-if="model.invName" style="margin-right: 10rpx;">{{ model.invName }}</view>
						<view v-if="!model.invName" style="margin-right: 10rpx;color: #eee;">请扫码或选择商品</view>
						<u-icon name="arrow-right"></u-icon>
					</view>
				</u-form-item>
				<!-- <u-form-item label="公司:" prop="cinvstd" label-width="180" :label-style="{ 'font-weight': 'bold' }">
					<view style="font-size: 30rpx;">{{ model.company?model.company.companyName:"" }}</view>
				</u-form-item> -->

				<u-form-item label="形象刊:" prop="cwhname" label-width="180" :label-style="{ 'font-weight': 'bold' }">
					<!-- <view>{{ model.cfree1 }}</view> -->
					<u-input v-model="model.freeVO.cfree1" type="text" placeholder="请输入" clearable />
				</u-form-item>

				<view style="display: flex;justify-content: space-between;">
					<view style="flex: 1;">
						<u-form-item label="上架货位:" prop="afterPosName" label-width="180" required
							:label-style="{ 'font-weight': 'bold'}">
							<!-- 	<u-input disabled placeholder="请扫描货位" v-model="model.afterPosName" type="text"
								maxlength="200"></u-input> -->
							<view @click="xzhw"
								style="display: flex;justify-content: space-between;width: 100%;font-size: 30rpx;">
								<view v-if="model.afterPosName" style="margin-right: 10rpx;">{{model.afterPosName}}
								</view>
								<view v-if="!model.afterPosName" style="margin-right: 10rpx;color: #eee;">请扫码或选择货位
								</view>
								<u-icon name="arrow-right"></u-icon>
							</view>
						</u-form-item>
					</view>
				</view>








				<u-form-item label="上架数量:" prop="iqty" label-width="180" required
					:label-style="{ 'font-weight': 'bold','color':'red' }">
					<!-- type="digit" -->
					<u-input v-model="model.iqty" type="number" placeholder="请输入上架数量" @input="replaceInput" clearable />
				</u-form-item>






			</u-form>
		</view>

		<!-- <view>
			<movable-area class="movable-area1">
				<movable-view class="movable-view" :x="x" :y="y" direction="all">
					<u-button size="mini" @click="handleFocus" type="success"
						style="width: 90px; height: 70px; color: #fff; ">
						<view style="font-size: 16px;display: flex; flex-direction: column;text-align: center;">
							<u-icon style="margin: auto;" name="/static/jeesite/sm1.png" size="80"></u-icon>
							<view>扫一扫</view>
						</view>
					</u-button>

				</movable-view>
			</movable-area>
		</view> -->

		<view>
			<movable-area class="movable-area">
				<movable-view class="movable-view" :x="x" :y="y" direction="all">
					<u-button size="mini" @click="submit" type="primary"
						style="width: 90px; height: 70px; color: #fff; font-size: 16px">确认上架
					</u-button>
				</movable-view>
			</movable-area>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				companySelectList: [],
				stockListHeight: 0,
				whSelectList: [],
				barCode: "", //AA01|01GD02001000I010|SPHC 2.0*262*C|Z11106202310301-4231031124239004|001|3380|1|202311011010|0AAA||202310301-4||9120963|11106||||||
				showflag: 0,
				model: {
					parent: {},
					freeVO: {}
				},
				xmflag: false,
				iqty: "",
				cposCodeAndName: "",
				cposcode: "", //货位号
				flag: false,
				focus: false,
				x: 650, //x坐标
				y: 650, //y坐标
			};
		},
		onLoad(params) {
			this.model.companyCode = this.vuex_company.companyCode || '';
			uni.$on('xzsp', (e) => {
				this.model.invCode = e.invCode
				this.model.invName = e.invName
				this.$forceUpdate()
			})

			uni.$on('hwObjs', (arr) => {
				if (arr.length) {
					this.model.afterPos = arr[0].id
					this.model.afterPosName = arr[0].name
					this.$forceUpdate()
				}
			})



			var _self = this;
			uni.getSystemInfo({
				success: (e) => {
					// resu 可以获取当前屏幕的高度
					_self.stockListHeight = e.windowHeight - uni.upx2px(160);
				},
				fail: (res) => {},
			});

		},
		watch: {},
		onShow() {
			// console.log('页面开启（onLoad）广播监听事件：xwscan')
			// 开启广播监听事件
			uni.$on('xwscan', this.BroadcastScanningToObtainData)
			

			this.$u.api.ktnw.companyTreeData().then(res => {
				this.companySelectList = res;
			});

			this.$u.api.ktnw.basWarehouseTreeData().then(res => {
				this.whSelectList = res;
			});
		},
		onHide() {
			// console.log('页面销毁（onUnload）广播监听事件：xwscan')
			// 销毁广播监听事件
			uni.$off('xwscan', this.BroadcastScanningToObtainData)
		},
		onUnload() {
			// console.log('页面销毁（onUnload）广播监听事件：xwscan')
			// 销毁广播监听事件
			uni.$off('xwscan', this.BroadcastScanningToObtainData)
		},
		onReady() {},
		computed: {
			...mapState(['vuex_basWare'])
		},
		methods: {
			selectcompanyConfirm() {
				this.model.invCode = ''
				this.model.invName = ''
				this.$forceUpdate()
			},
			replaceInput(e) {
				console.log(e);
				var that = this
				e = e.match(/^\d*(\.?\d{0,2})/g)[0]
				this.$nextTick(() => {
					that.model.iqty = e
				})

			},
			/** 发生声音*/
			sendMp3(name) {
				console.log("=====testClick=====");
				let src = '/static/jeesite/' + name + '.mp3';
				//实例化声音  
				const Audio = uni.createInnerAudioContext();
				Audio.autoplay = true;
				Audio.src = src; //音频地址  
				Audio.play(); //执行播放  
				Audio.onError((res) => {
					console.log(res.errMsg);
					console.log(res.errCode);
				});
				Audio.onPause(function() {
					console.log('end');
					Audio.destroy();
				});
			},
			selectConfirm() {
				this.model.afterPos = ''
				this.model.afterPosName = ''
				this.$forceUpdate()
			},
			handleFocus() {
				var _that = this;
				_that.focus = false;
				setTimeout(() => {
					_that.focus = true;
				}, 500)
			},
			xzsp() {
				if (!this.model.companyCode) {
					this.$u.toast('请先选择公司！');
					// this.$refs.jsError.showError("", "请先选择公司", "error");
				}else{
					uni.navigateTo({
						url: "/pages/ktnw/qtsj/xzspList?companyCode=" + this.model.companyCode,
					});
				}
				
			},
			xzhw() {
				if (!this.model.whcode) {
					this.$u.toast('请先选择仓库！');
					return;
				}
				uni.navigateTo({
					url: "/pages/ktnw/qtsj/hwXz?whcode=" + this.model.whcode,
				});
			},
			region() {
				uni.navigateTo({
					url: "/pages/asd/index/cgsj/region?cwhcode=" + this.model.cwhcode,
				});
			},
			invCode(bar, companyCode) {
				let InventoryPrefix = this.vuex_config.InventoryPrefix;
				if (bar.indexOf(InventoryPrefix) != -1) {
					return bar
				} else {
					let code = `inv_${companyCode}_${bar}`
					return code
				}
			},
			BroadcastScanningToObtainData(res) {
				//获取扫描到的条形码
				let barcode = res.code
				
				//判断条形码长度是否大于3
				if(barcode.length > 3){
					//去除换行符
					let newString = barcode.replace('\n;', '');
					
					this.barCode = newString;
					this.confirm()
					//将换行符分割成数组
					// const allItems = newString.split('\n');
					// 	//遍历数组，将每一项添加到arr中
					// 	for(let i = 0;i<allItems.length;i++){
					// 		this.arr.push({
					// 			"content":allItems[i],
					// 			"remarks":this.remarks
					// 		})
					// 	}
				}
			},
			confirm() {
				let _that = this;
				_that.focus = false
				let InventoryPrefix = _that.vuex_config.InventoryPrefix;
				let PositionPrefix = _that.vuex_config.PositionPrefix;
				let InvBarType = _that.vuex_config.InvBarType;
				let PosBarType = _that.vuex_config.PosBarType;
				let bar = encodeURIComponent(this.barCode)

				// if (bar.indexOf(InventoryPrefix) != -1) {
				// 	this.$u.api.ktnw.getBarInfo({
				// 		barCode: bar,
				// 		barType: InvBarType
				// 	}).then((res) => {
				// 		if(res.result == 'true'){
				// 			_that.sendMp3('cg');
				// 			setTimeout(() => {
				// 				_that.focus = true;
				// 			}, 500)
				// 			this.model.invCode = res.data.basInv.invCode
				// 			this.model.invName = res.data.basInv.invName
				// 			this.model.companyCode = res.data.basInv.companyCode
				// 			this.model.company = res.data.basInv.company
				// 			this.$forceUpdate()

				// 		}else{
				// 			_that.sendMp3('sb');
				// 			let message = res.message
				// 			_that.$refs.jsError.showError("", message, "error");
				// 			setTimeout(() => {
				// 				_that.focus = true;
				// 			}, 500)
				// 		}
				// 		this.barCode = ''

				// 	})
				// }else 
				if (bar.indexOf(PositionPrefix) != -1) {
					this.$u.api.ktnw.getBarInfo({
						barCode: bar,
						barType: PosBarType,
						whCode: this.model.whcode || ''
					}).then((res) => {
						if (res.result == 'true') {
							if(res.data?.basPos?.treeLeaf == '0') {
								this.$forceUpdate()
								_that.sendMp3('sb');
								let message = '请扫描末级货位'
								_that.$refs.jsError.showError("", message, "error");
								return;
							}							
							_that.sendMp3('cg');
							setTimeout(() => {
								_that.focus = true;
							}, 500)
							this.model.whcode = res.data.basWare.cwhcode
							this.model.afterPos = res.data.basPos.posCode
							this.model.afterPosName = res.data.basPos.posName
							this.$forceUpdate()

						} else {
							_that.sendMp3('sb');
							let message = res.message
							_that.$refs.jsError.showError("", message, "error");
							setTimeout(() => {
								_that.focus = true;
							}, 500)
						}
						this.barCode = ''
					})
				} else {
					if (!this.model.companyCode) {
						_that.sendMp3('sb');
						_that.$refs.jsError.showError("", "请先选择公司", "error");
						setTimeout(() => {
							_that.focus = true;
							_that.barCode = ''
						}, 500)
					} else {
						let barCode = this.invCode(bar, this.model.companyCode)
						this.$u.api.ktnw.getBarInfo({
							barCode: barCode,
							barType: InvBarType,
							companyCode: this.model.companyCode
						}).then((res) => {
							if (res.result == 'true') {
								if(res.data.basInv){
									_that.sendMp3('cg');
									setTimeout(() => {
										this.barCode = ''
										_that.focus = true;
									}, 500)
									this.model.invCode = res.data.basInv.invCode
									this.model.invName = res.data.basInv.invName
									// this.model.companyCode = res.data.basInv.companyCode
									// this.model.company = res.data.basInv.company
									this.$forceUpdate()
								}else{
									_that.sendMp3('sb');
									let message = '请扫描正确的商品编码'
									_that.$refs.jsError.showError("", message, "error");
								}

							} else {
								_that.sendMp3('sb');
								let message = res.message
								_that.$refs.jsError.showError("", message, "error");
								setTimeout(() => {
									this.barCode = ''
									_that.focus = true;
								}, 500)
							}
							this.barCode = ''

						})
					}
				}

			},
			search() {
				var _that = this;
				_that.focus = false
				uni.scanCode({
					scanType: ["barCode", "qrCode"],
					// onlyFromCamera: true,
					success: function(res) {
						_that.barCode = res.result;
						_that.confirm()
					},
				});
			},
			async submit() {
				if (!this.model.invCode) {
					this.$refs.jsError.showError("", "请先扫描商品", "error");
					return;
				}


				if (!this.model.afterPosName) {
					this.$refs.jsError.showError("", "请先扫描上架货位", "error");
					return;
				}


				if (!this.model.iqty) {
					this.$refs.jsError.showError("", "请输入上架数量", "error");
					return;
				}

				if (this.model.iqty <= 0) {
					// this.$u.toast('入库数量不能小于等于零！');
					this.$refs.jsError.showError("", "数量不能小于等于零", "error");
					return;
				}

				let data = {
					parent: {
						whcode: this.model.whcode
					},
					freeVO: {
						cfree1: this.model.freeVO.cfree1
					},
					companyCode: this.model.companyCode,
					invCode: this.model.invCode,
					invName: this.model.invName,
					beforePos: '/',
					afterPos: this.model.afterPos,
					iqty: this.model.iqty,
				};

				console.log(data);
				this.$u.api.ktnw.posUpSave(data).then((res) => {

					if (res.result == "true") {
						this.$u.toast(res.message);
						this.model = {
							parent: {},
							freeVO: {}
						}
						// this.sendMp3('sjcg');
						// this.handleFocus()
					} else {
						this.$refs.jsError.showError("", res.message, "error");

					}
				});
			},

			checkData() {
				const _this = this;
				return new Promise((resolve, reject) => {
					if (_this.cposcode == undefined || _this.cposcode == "") {
						_this.$refs.jsError.showError("", "请选择货位！", "error");
						resolve("err");
					}
					if (!_this.flag) {
						_this.$refs.jsError.showError("", "请验证现品票！", "error");
						resolve("err");
					}
					resolve("suc");
				});
			},
		},
	};
</script>
<style lang="scss">
	$all_width: 96rpx;
	$all_height: 96rpx;

	.movable-area2 {
		z-index: 999;
		height: 97vh;
		width: 650rpx;
		position: fixed;
		right: $all_width;
		top: -($all_height + 220rpx);
		pointer-events: none; //此处要加，鼠标事件可以渗透

		.movable-view {
			width: $all_width;
			height: $all_height;
			pointer-events: auto; //恢复鼠标事件

			image {
				width: $all_width;
				height: $all_height;
			}
		}
	}

	.movable-area1 {
		z-index: 888;
		height: 97vh;
		width: 650rpx;
		position: fixed;
		right: $all_width;
		top: -($all_height + 70rpx);
		pointer-events: none; //此处要加，鼠标事件可以渗透

		.movable-view {
			width: $all_width;
			height: $all_height;
			pointer-events: auto; //恢复鼠标事件

			image {
				width: $all_width;
				height: $all_height;
			}
		}
	}

	.movable-area {
		z-index: 999;
		height: 97vh;
		width: 650rpx;
		// max-width: 1152rpx;
		// 固定在右边
		top: -20rpx;
		position: fixed;
		right: $all_width;
		// 固定在右下角
		pointer-events: none; //此处要加，鼠标事件可以渗透

		.movable-view {
			width: $all_width;
			height: $all_height;
			pointer-events: auto; //恢复鼠标事件

			image {
				width: $all_width;
				height: $all_height;
			}
		}
	}
</style>